package com.print;

import java.io.IOException;
import java.util.Vector;

import mycoffee.order.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioButton;
import com.citizen.port.android.BluetoothPort;
import com.citizen.request.android.RequestHandler;

public class PrinterSettingDialog extends Activity {
	// declare component object
	RadioButton radGoodcom;
	RadioButton radCitizen;
	Button btScanDevice;
	// Intent request codes
	// private static final int REQUEST_CONNECT_DEVICE = 1;
	private static final int REQUEST_ENABLE_BT = 2;
	public static final String BT_DEVICE_ADDRESS = "DefaultDevice";
	private String currentDeviceAddress;
	ArrayAdapter<String> adapter;
	private BluetoothAdapter mBluetoothAdapter;
	private Vector<BluetoothDevice> remoteDevices;
	private BroadcastReceiver searchFinish;
	private BroadcastReceiver searchStart;
	private BroadcastReceiver discoveryResult;
	private Thread hThread;
	private static boolean connected;
	// UI
	private ListView list;
	// BT
	private BluetoothPort bp;
	private ProgressDialog dialog;

	/**
	 * Set up Bluetooth.
	 */
	private void bluetoothSetup() {
		// Initialize
		clearBtDevData();
		bp = BluetoothPort.getInstance();
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		if (mBluetoothAdapter == null) {
			// Device does not support Bluetooth
			return;
		}
		if (!mBluetoothAdapter.isEnabled()) {
			Intent enableBtIntent = new Intent(
					BluetoothAdapter.ACTION_REQUEST_ENABLE);

			startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
		}
	}

	private void clearBtDevData() {
		remoteDevices = new Vector<BluetoothDevice>();
	}

	// Bluetooth Connection method.
	private void btConn(final BluetoothDevice btDev) throws IOException {
		currentDeviceAddress = btDev.getAddress();
		new connTask().execute(btDev);
	}

	/** ======================================================================= */
	public class connTask extends AsyncTask<BluetoothDevice, Void, Integer> {
		private final ProgressDialog dialog = new ProgressDialog(
				PrinterSettingDialog.this);

		@Override
		protected void onPreExecute() {
			dialog.setTitle("Bluetooth");
			dialog.setMessage("Connecting");
			dialog.show();
			super.onPreExecute();
		}

		@Override
		protected Integer doInBackground(BluetoothDevice... params) {
			Integer retVal = null;
			try {
				bp.connect(params[0]);
				retVal = new Integer(0);
			} catch (IOException e) {
				retVal = new Integer(-1);
			}
			return retVal;
		}

		@Override
		protected void onPostExecute(Integer result) {
			if (result.intValue() == 0) {
				RequestHandler rh = new RequestHandler();
				hThread = new Thread(rh);
				hThread.start();
				connected = true;
				// UI
				list.setEnabled(false);
				btScanDevice.setEnabled(false);
			}
			if (dialog.isShowing()) {
				String cmsg;
				dialog.dismiss();
				if (connected) {
					// Save to config as default device
					SharedPreferences settings = getSharedPreferences(
							BT_DEVICE_ADDRESS, 0);
					SharedPreferences.Editor editor = settings.edit();
					editor.putString("deviceAddress", currentDeviceAddress);

					// Commit the edits!
					editor.commit();

					cmsg = "Bluetooth Connected";
					showErrorDialog(cmsg);
					// Toast toast = Toast.makeText(PrinterSettingDialog.this,
					// cmsg,
					// Toast.LENGTH_LONG);
					// toast.show();
					// finish();
				} else {
					cmsg = "Bluetooth Not Connected.";
					AlertView.showError(cmsg, PrinterSettingDialog.this);
					// finish();
				}
			}
			super.onPostExecute(result);
		}
	}

	/**
	 * Bluetooth connection status.
	 * 
	 * @return connected - boolean
	 */
	public static boolean isConnected() {
		return connected;
	}

	// ==================================================================================================//
	// ==================================================================================================//

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.print_setting);
		setTitle(getString(R.string.print_setting));	
		
		// Setting
		bluetoothSetup();
		dialog = new ProgressDialog(PrinterSettingDialog.this);
		radGoodcom = (RadioButton) findViewById(R.id.radGoodcom);
		radCitizen = (RadioButton) findViewById(R.id.radCitizen);
		list = (ListView) findViewById(R.id.ListView01);

		btScanDevice = (Button) findViewById(R.id.btScanPrinter);
		// Search Button
		btScanDevice.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!mBluetoothAdapter.isDiscovering()) {
					clearBtDevData();
					adapter.clear();
					dialog.setTitle(getString(R.string.printer));
					dialog.setMessage(getString(R.string.scanning));
					dialog.show();
					mBluetoothAdapter.startDiscovery();
				} else {
					dialog.dismiss();
					mBluetoothAdapter.cancelDiscovery();
				}
			}
		});
		// Bluetooth Device List
		adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1);
		list.setAdapter(adapter);
		// Connect -
		list.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				BluetoothDevice btDev = remoteDevices.elementAt(arg2);
				try {
					if (radCitizen.isChecked()
							&& btDev.getName().equals("Mobile Printer")) {
						if (!mBluetoothAdapter.isDiscovering()) {
							btConn(btDev);
							// finish();
						} else {
							return;
						}
					} else if (radGoodcom.isChecked()
							&& btDev.getName().equals("MPT-58")) {
						if (!mBluetoothAdapter.isDiscovering()) {
							btConn(btDev);
							// finish();
						} else {
							return;
						}

					} else {
						showErrorDialog(getString(R.string.wrong_printer));
					}

				} catch (IOException e) {
					AlertView.showError(e.getMessage(), PrinterSettingDialog.this);
					return;
				}
			}
		});

		// UI - Event Handler.
		// Search device, then add List.
		discoveryResult = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				String key;
				BluetoothDevice remoteDevice = intent
						.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				if (remoteDevice != null) {
					key = remoteDevice.getName() + "\n["
							+ remoteDevice.getAddress() + "]";

					remoteDevices.add(remoteDevice);
					adapter.add(key);
				}
			}
		};
		registerReceiver(discoveryResult, new IntentFilter(
				BluetoothDevice.ACTION_FOUND));
		searchStart = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				btScanDevice.setText("Stop Searching Device");
			}
		};
		registerReceiver(searchStart, new IntentFilter(
				BluetoothAdapter.ACTION_DISCOVERY_STARTED));
		searchFinish = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				dialog.dismiss();
				btScanDevice.setText("Search Device");
			}
		};
		registerReceiver(searchFinish, new IntentFilter(
				BluetoothAdapter.ACTION_DISCOVERY_FINISHED));
	}

	/**
	 * Show Error Dialog
	 * 
	 * @param string
	 */
	private void showErrorDialog(String msg) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(msg);
		final String message = msg;
		builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				if (message.equals("Bluetooth Connected")) {
					finish();
				}
			}
		});
		builder.show();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();		
		unregisterReceiver(searchFinish);
		unregisterReceiver(searchStart);
		unregisterReceiver(discoveryResult);
	}
}
